const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

async function setupMySQL() {
    console.log('=== MySQL数据库设置向导 ===\n');

    // 询问MySQL root密码
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    const password = await new Promise(resolve => {
        rl.question('请输入MySQL root密码 (如果没有密码请直接回车): ', answer => {
            resolve(answer);
            rl.close();
        });
    });

    console.log('\n正在连接MySQL...');

    try {
        // 创建连接（不指定数据库）
        const connection = await mysql.createConnection({
            host: 'localhost',
            port: 3306,
            user: 'root',
            password: password
        });

        console.log('✓ MySQL连接成功');

        // 创建数据库
        await connection.execute(`
            CREATE DATABASE IF NOT EXISTS endo_sight_uc
            CHARACTER SET utf8mb4
            COLLATE utf8mb4_unicode_ci
        `);
        console.log('✓ 数据库 endo_sight_uc 创建成功');

        // 检查数据库是否存在
        const [databases] = await connection.execute('SHOW DATABASES LIKE "endo_sight_uc"');
        if (databases.length > 0) {
            console.log('✓ 数据库验证成功');
        }

        await connection.end();

        // 更新.env文件
        const envPath = path.join(__dirname, '.env');
        let envContent = '';

        // 读取现有.env内容
        if (fs.existsSync(envPath)) {
            envContent = fs.readFileSync(envPath, 'utf8');
        }

        // 更新数据库配置
        const newConfig = `# 数据库配置
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=${password}
DB_NAME=endo_sight_uc`;

        // 替换数据库配置部分
        const dbConfigStart = envContent.indexOf('# 数据库配置');
        if (dbConfigStart !== -1) {
            const dbConfigEnd = envContent.indexOf('\n\n', dbConfigStart);
            if (dbConfigEnd !== -1) {
                envContent = envContent.substring(0, dbConfigStart) +
                            newConfig +
                            envContent.substring(dbConfigEnd);
            } else {
                envContent = envContent.substring(0, dbConfigStart) + newConfig;
            }
        } else {
            envContent = newConfig + '\n' + envContent;
        }

        // 备份并写入
        if (fs.existsSync(envPath)) {
            fs.copyFileSync(envPath, envPath + '.backup');
            console.log('✓ 原有.env文件已备份为 .env.backup');
        }

        fs.writeFileSync(envPath, envContent);
        console.log('✓ .env文件配置完成');

        console.log('\n=== 设置完成 ===');
        console.log('数据库配置已更新，现在可以启动服务器了！');
        console.log('\n启动命令:');
        console.log('npm start');

    } catch (error) {
        console.error('\n❌ 设置失败:', error.message);
        if (error.code === 'ER_ACCESS_DENIED_ERROR') {
            console.log('\n可能的解决方案:');
            console.log('1. 检查MySQL服务是否运行');
            console.log('2. 确认root密码是否正确');
            console.log('3. 如果忘记密码，需要重置MySQL root密码');
        }
        process.exit(1);
    }
}

setupMySQL();